<template>
	<view class="uni-container">
		<view class="header">
			<view class="back">
				<view @click="navigateBack" style="margin-left: 15px;display: flex;align-items: center;color: #fff;">
					<uni-icons type="back" size="24" color="#fff"></uni-icons>
					<text>返回</text>
				</view>
			</view>
		</view>
		<!-- 地图弹窗 -->
		<uni-popup ref="mapPopup">
			<view
				style="width: 3000rpx;height: 1800rpx;background: #fff;position: relative;border-radius: 50rpx;overflow: hidden;">
				<web-view style="width: 100%;height: 100%;" :fullscreen="false"
					src="https://lbs.qq.com/getPoint/"></web-view>
			</view>
		</uni-popup>
		<!-- 媒体库弹窗 -->
		<uni-drawer class="insert-image-drawer" v-if="drawerWidth" ref="insertImageDrawer" mode="right"
			:width="drawerWidth">
			<uni-media-library mode="picker" :selected-count="state == 0?6:1" :media-tabs="['image']"
				@onInsert="onInsertCover"></uni-media-library>
		</uni-drawer>
		<view class="w-100 flex-dir-col ali-item-cen">
			<uni-forms style="background: #fff;" ref="form" :model="formData" validateTrigger="bind">
				<uni-forms-item name="audit_status" label="审核状态">
					<uni-data-checkbox v-model="formData.audit_status"
						:localdata="auditStatusRange"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item required name="name" label="标题">
					<uni-easyinput placeholder="活动名称" v-model="formData.name"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item required name="content" label="详情">
					<view style="border: 1rpx solid #F0F0F0;padding: 0 30rpx;">
						<editor-component @textchange="onTextChange" @ready="onEditorReady"></editor-component>
					</view>
					<!-- <uni-easyinput placeholder="活动详情" v-model="formData.content"></uni-easyinput> -->
				</uni-forms-item>
				<uni-forms-item required name="imgs" label="图片">
					<!-- <uni-file-picker :limit="6" return-type="array" v-model="formData.imgs"></uni-file-picker> -->
					<view style="display: flex;flex-direction: row;flex-wrap: wrap;">
						<view
							style="position: relative;width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;margin-right: 30rpx;margin-bottom: 30rpx;"
							v-if="formData.imgs.length > 0" v-for="(img,index) in formData.imgs" :key="index">
							<view
								style="position: absolute;right: 10rpx;top: 10rpx;z-index: 1;background: #6666667d;border-radius: 200rpx;width: 50rpx;height: 50rpx;line-height: 50rpx;"
								@click="() => removeThumbnail(0,index)">
								<uni-icons type="closeempty" size="16" color="#ffffff"></uni-icons>
							</view>
							<image style="width: 150px;height: 150px;position: absolute;top:0;left: 0;" :src="img.src">
							</image>
						</view>
						<view v-if="formData.imgs.length <6" @click="() => openInsertImageDrawer(0)"
							style="width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;">
							<uni-icons class="placeholder" type="plusempty" size="60" color="#e8e8e8"></uni-icons>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item name="tags" label="标签">
					<uni-data-checkbox :max="6" :multiple="true" v-model="formData.tags" collection="qmy-activity-tags"
						field="name as text, name as value"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item required name="type" label="分类">
					<uni-data-picker v-model="formData.type" collection="qmy-activity-class"
						field="name as text, _id as value"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item required name="signup_start_time" label="报名开始时间">
					<uni-datetime-picker return-type="timestamp"
						v-model="formData.signup_start_time"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required name="signup_end_time" label="报名结束时间">
					<uni-datetime-picker return-type="timestamp"
						v-model="formData.signup_end_time"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required name="start_time" label="活动开始时间">
					<uni-datetime-picker return-type="timestamp" v-model="formData.start_time"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required name="end_time" label="活动结束时间">
					<uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item required name="location" label="活动地点">
					<uni-easyinput placeholder="活动地点" v-model="formData.location"></uni-easyinput>
					<view style="font-size: 24rpx;color: #757575;margin-top: 20rpx;" @click="openMap">获取经纬度及地点，
						<text style="color: #42cdff;">打开地图</text>
					</view>
				</uni-forms-item>
				<uni-forms-item required name="location_lat" label="地点纬度">
					<uni-easyinput placeholder="地点纬度" v-model="formData.location_lat"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item required name="location_lng" label="地点经度">
					<uni-easyinput placeholder="地点经度" v-model="formData.location_lng"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="is_pay" label="是否付费">
					<switch @change="binddata('is_pay', $event.detail.value)" :checked="formData.is_pay"></switch>
				</uni-forms-item>
				<uni-forms-item name="pay_amount" label="活动费用">
					<uni-easyinput placeholder="活动费用" type="number" v-model="formData.pay_amount"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item required name="people_num" label="活动人数">
					<uni-easyinput placeholder="活动人数" type="number" v-model="formData.people_num"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item required name="contact_phone" label="联系电话">
					<uni-easyinput v-model="formData.contact_phone" trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="group_qrcode" label="群聊二维码">
					<!-- <uni-file-picker file-mediatype="image" :limit="1" return-type="array"
						v-model="formData.group_qrcode"></uni-file-picker> -->
					<view style="display: flex;flex-direction: row;flex-wrap: wrap;">
						<view
							style="position: relative;width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;margin-right: 30rpx;margin-bottom: 30rpx;"
							v-if="formData.group_qrcode.length > 0" v-for="(img,index) in formData.group_qrcode"
							:key="index">
							<view
								style="position: absolute;right: 10rpx;top: 10rpx;z-index: 1;background: #6666667d;border-radius: 200rpx;width: 50rpx;height: 50rpx;line-height: 50rpx;"
								@click="() => removeThumbnail(1,index)">
								<uni-icons type="closeempty" size="16" color="#ffffff"></uni-icons>
							</view>
							<image style="width: 150px;height: 150px;position: absolute;top:0;left: 0;" :src="img.src">
							</image>
						</view>
						<view v-if="formData.group_qrcode.length <1" @click="() => openInsertImageDrawer(1)"
							style="width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;">
							<uni-icons class="placeholder" type="plusempty" size="60" color="#e8e8e8"></uni-icons>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item name="sort" label="排序">
					<uni-easyinput placeholder="排序" type="number" v-model="formData.sort"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="is_recommend" label="精选">
					<switch @change="binddata('is_recommend', $event.detail.value)" :checked="formData.is_recommend">
					</switch>
				</uni-forms-item>
				<view class="uni-button-group">
					<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
					<navigator open-type="navigateBack" style="margin-left: 15px;">
						<button class="uni-button" style="width: 100px;">返回</button>
					</navigator>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/qmy-activity.js';

	// 引入编辑器组件
	import EditorComponent from "@/uni_modules/uni-cms/components/editor/editor.vue";

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'qmy-activity';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		components: {
			EditorComponent
		},
		data() {
			let formData = {
				"name": "",
				"content": "",
				"imgs": [],
				"tags": [],
				"type": "",
				"signup_start_time": null,
				"signup_end_time": null,
				"start_time": null,
				"end_time": null,
				"location": "",
				"location_lat": "",
				"location_lng": "",
				"is_pay": null,
				"pay_amount": null,
				"people_num": null,
				"contact_name": "",
				"contact_phone": "",
				"group_qrcode": [],
				"sort": null,
				"is_recommend": null,
				"audit_status": null
			}
			return {
				drawerWidth: 0, // 插入图片抽屉宽度
				state: 0,
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				auditStatusRange: [{
					text: '审核中',
					value: 0
				}, {
					text: '审核通过',
					value: 1
				}, {
					text: '审核不通过',
					value: 2
				}]
			}
		},
		mounted() {
			const sysinfo = uni.getSystemInfoSync()
			this.drawerWidth = sysinfo.windowWidth * .8
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			openInsertImageDrawer(e) {
				this.state = e;
				if (e == 0) {
					if (this.formData.imgs.length >= 6) {
						uni.showToast({
							title: '最多只能选择6张图片',
							icon: 'none',
							mask: true
						})
					} else {
						this.$refs.insertImageDrawer.open()
					}
				} else {
					if (this.formData.group_qrcode.length >= 1) {
						uni.showToast({
							title: '最多只能选择1张图片',
							icon: 'none',
							mask: true
						})
					} else {
						this.$refs.insertImageDrawer.open()
					}
				}
			},
			async onInsertCover(selectMediaItems) {
				if (this.state == 0) {
					selectMediaItems.forEach(item => {
						if (this.formData.imgs.length == 6) {
							return uni.showToast({
								title: '最多只能选择6张图片',
								icon: 'none'
							})
						} else {
							this.formData.imgs.push(item)
						}
					})
					this.$refs.insertImageDrawer.close()
				} else {
					selectMediaItems.forEach(item => {
						if (this.formData.group_qrcode.length == 1) {
							return uni.showToast({
								title: '最多只能选择1张图片',
								icon: 'none'
							})
						} else {
							this.formData.group_qrcode.push(item)
						}
					})
					this.$refs.insertImageDrawer.close()
				}
			},
			removeThumbnail(e, index) {
				this.state = e;
				// 删除指定索引的图片
				if (this.state == 0) {
					if (index >= 0 && index < this.formData.imgs.length) {
						this.formData.imgs.splice(index, 1); // 删除 index 位置的元素
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '无效的索引',
							icon: 'none'
						});
					}
				} else {
					if (index >= 0 && index < this.formData.group_qrcode.length) {
						this.formData.group_qrcode.splice(index, 1); // 删除 index 位置的元素
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '无效的索引',
							icon: 'none'
						});
					}
				}
			},
			openMap() {
				this.$refs.mapPopup.open('center')
			},
			// 监听富文本编辑器内容变化
			onTextChange(e) {
				this.editorCtx.getContents({
					success: (e) => {
						this.formData.content = e.html
					}
				})
			},

			// 富文本编辑器初始化完成后触发
			onEditorReady(editorCtx) {
				if (!editorCtx) return

				// 保存editorCtx
				this.editorCtx = editorCtx
				// 设置编辑器内容
				this.$nextTick(() => {
					this.setContents()
				})

			},

			/**
			 * 设置编辑器内容
			 */
			setContents() {
				// 检查编辑器上下文是否存在
				if (this.editorCtx && this.formData.content) {
					// #ifdef H5
					// 如果是H5平台，则直接使用formData中的内容
					const content = this.formData.content
					// #endif

					// #ifndef H5
					// 如果不是H5平台，则需要将formData中的内容转换为编辑器所需的格式
					const content = translateInputContent(this.formData.content)
					// #endif
					// 设置编辑器内容
					this.editorCtx.setContents({
						html: content
					})
				}
			},

			// 返回上一页或跳转到首页
			navigateBack() {
				const pages = getCurrentPages()

				if (pages.length > 1) {
					// 返回上一页
					uni.navigateBack(-1)
				} else {
					// 跳转到文章列表页
					uni.redirectTo({
						url: '/pages/index/index'
					})
				}
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"name,content,user_id,imgs,tags,type,signup_start_time,signup_end_time,start_time,end_time,location,location_lat,location_lng,is_pay,pay_amount,people_num,contact_name,contact_phone,group_qrcode,sort,is_recommend,audit_status"
				).get().then((res) => {
					const data = res.result.data[0]
					// 获取发布用户端联系方式
					if (!data.contact_phone) {
						db.collection("uni-id-users").doc(data.user_id).field("mobile").get().then((lus) => {
							if (lus.result.data[0].mobile) {
								data.contact_phone = lus.result.data[0].mobile
							}
							if (data) {
								this.formData = data
								this.$nextTick(() => {
									this.setContents()
								})
							}
						})
					} else {
						if (data) {
							this.formData = data
							this.$nextTick(() => {
								this.setContents()
							})
						}
					}

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style lang="scss">
	@import '@/uni_modules/uni-cms/common/style/article-detail.scss';

	.uni-container {
		background: #f8f8f8;
		padding-bottom: 66px;
		margin-top: 54px;

		.header {
			width: 950px;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			margin: 0 auto;
			z-index: 999;
			height: 60px;
			display: flex;
			align-items: center;

			.back {
				cursor: pointer;
				color: #333;
			}
		}
	}

	::v-deep .uni-forms {
		width: 35%;
		padding: 100rpx;
		border-radius: 20rpx;
	}

	::v-deep .editor-toolbar {
		z-index: 1000 !important;
	}

	::v-deep .uni-popup {
		z-index: 1001;
	}

	::v-deep .uni-drawer {
		z-index: 1002;
	}
</style>